<template>
  <div class="server-module-box">
    <div class="server-module" v-if="curModule?.children?.length">
      <div class="server-title">概览</div>
      <div class="server-list">
        <div class="server-item" v-for="item in curModule.children" :key="item.id" @click="redirectPath(item)">
          <div class="top">
            <div class="top-right">
              <span class="title">{{ item.title }}</span>
              <span class="des">{{ item.description || item.title }}</span>
            </div>
          </div>
          <div class="bottom">管理</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { toRefs, computed, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

const props = defineProps({
  curModule: {
    type: Object,
    default: () => {}
  },
  rowNum: {
    type: Number,
    default: 4
  }
})
const { curModule, rowNum } = toRefs(props)

//重定向到最后一级子路由(可能会跨模块)
const token = computed(() => store.state.base.token)
const pathMapping = computed(() => store.state.base.pathMapping)
const firstMenu = ref(null)

const redirectPath = menu => {
  if (!firstMenu.value) {
    firstMenu.value = menu
  }
  if (menu.children?.length > 0 && menu.type !== 2) {
    redirectPath(menu.children[0])
  } else {
    // 判断是否进入子系统系统（拿到映射中对应路由的完整地址，比对与当前路由是否相同）
    const isSame = compareURLs(pathMapping.value[menu.path], location.href)
    firstMenu.value.path = menu.path
    addToRecentlyVisited(firstMenu.value)
    if (!isSame) {
      const url = `${pathMapping.value[menu.path]}?code=${token.value}`
      window.open(url, '_blank')
    } else {
      router.push({ path: menu.path })
    }
  }
}

// 路由完整地址比对
const compareURLs = (urlA, urlB) => {
  const { hostname: hostA, port: portA, pathname: pathnameA } = new URL(urlA)
  const { hostname: hostB, port: portB, pathname: pathnameB } = new URL(urlB)
  return hostA === hostB && portA === portB && pathnameA === pathnameB
}

// 添加最近访问记录的函数
const addToRecentlyVisited = (item) => {
  // 从localStorage获取现有记录
  let recentlyVisited = JSON.parse(localStorage.getItem('recently_visited') || '[]')
  
  // 检查是否已存在相同记录
  const existingIndex = recentlyVisited.findIndex(i => i.path === item.path)
  if (existingIndex !== -1) {
    // 如果存在,删除旧记录
    recentlyVisited.splice(existingIndex, 1)
  }
  
  // 添加新记录到开头
  recentlyVisited.unshift(item)
  
  // 只保留最近8条记录
  recentlyVisited = recentlyVisited.slice(0, 8)
  
  // 保存回localStorage
  localStorage.setItem('recently_visited', JSON.stringify(recentlyVisited))
  firstMenu.value = null
}
</script>
<style scoped lang='scss'>
.server-module-box{
  .server-module{
    padding: 10px 30px 30px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: flex-start;
    .server-title{
      font-size: 18px;
      color: #333;
      position: relative;
      margin-bottom: 20px;
      &::before{
        content: '';
        position: absolute;
        left: -10px;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 60%;
        opacity: 0.7;
        background-color: $mainColor;
      }
    }
    .server-list {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      box-sizing: border-box;
      gap: 20px;
      .server-item {
        width: calc((100% - (20px * (v-bind(rowNum) - 1))) / v-bind(rowNum));
        position: relative;
        max-width: 296px;
        min-width: 160px;
        background-color: $homeBgColor;
        border: 1px transparent solid;
        border-radius: 4px;
        box-sizing: border-box;
        transition: box-shadow .15s;
        &:hover{
          border: 1px rgba(170, 170, 170, 0.4) solid;
          box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.16);
        }
        .top{
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 80px;
          padding: 12px 15px;
          box-sizing: border-box;
          cursor: pointer;
          .top-left{
            i{
              font-size: 40px;
              margin-left: 10px;
              margin-right: 40px;
              color: #4D99F2;
            }
          }
          .top-right{
            display: flex;
            flex-direction: column;
            align-items: center;
            .title{
              margin-bottom: 5px;
              line-height: 24px;
              font-size: 16px;
              font-weight: bold;
              color: #333;
            }
            .des{
              color: #888;
              font-size: 13px;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
        .bottom{
          height: 47px;
          line-height: 46px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-top: 1px solid #eceaea;
          box-sizing: border-box;
          font-size: 14px;
          cursor: pointer;
          // &:hover{
          //   background-color: $mainColor;
          //   color: #fff;
          // }
        }
      }
      .server-item:hover .server-item-logo {
        transform: translateY(-5px); /* 向上移动5px */
      }
    }
  }
}
</style>